<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--分类数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="typeName" placeholder="请输入组卷分类名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="typeTreeOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--文档数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="文档名称" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入文档名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="管理单位" prop="unitId">
                <el-select v-model="queryParams.unitId" placeholder="请选择管理单位" clearable>
                  <el-option
                    v-for="dict in unitOptions"
                    :key="dict.unitId"
                    :label="dict.name"
                    :value="dict.unitId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="文档类型" prop="docType">
                <el-select v-model="queryParams.docType" placeholder="请选择文档类型" clearable>
                  <el-option label="PDF型" value="1" />
                  <el-option label="图片型" value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="文档位置" prop="loc">
                <el-input
                  v-model="queryParams.loc"
                  placeholder="请输入文档位置"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['system:doc:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['system:doc:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['system:doc:remove']"
                >删除</el-button>
              </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:doc:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleBatchUpload"
          v-hasPermi="['system:doc:add']"
        >文档批量上传</el-button>
      </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="docList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="文档名称" align="center" prop="name" />
              <el-table-column label="文档类型" align="center" prop="docType">
                <template slot-scope="scope">
                  {{getDocTypeName(scope.row.docType)}}
                </template>
              </el-table-column>
              <el-table-column label="组卷类别" align="center" prop="typeId">
                <template slot-scope="scope">
                  {{getType(scope.row.typeId)}}
                </template>
              </el-table-column>
              <el-table-column label="管理单位" align="center" prop="unitId">
                <template slot-scope="scope">
                  {{getUnit(scope.row.unitId)}}
                </template>
              </el-table-column>
              <el-table-column label="文档位置" align="center" prop="loc" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleView(scope.row)"
                    v-hasPermi="['system:doc:query']"
                  >查看</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:doc:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['system:doc:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>


    <!-- 添加或修改文档对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="disabled">
        <el-form-item label="组卷类别" prop="typeId">
          <treeselect :disabled="disabled" v-model="form.typeId" :options="typeTreeOptions" :show-count="true" placeholder="请选择组卷类别" />
        </el-form-item>
        <el-form-item label="文档类型" prop="docType">
          <el-select :disabled="disabled" v-model="form.docType" placeholder="请选择文档类型" @change="handleDocTypeChange">
            <el-option label="PDF型" value="1" />
            <el-option label="图片型" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="文档名称" prop="name">
          <el-input :disabled="disabled" v-model="form.name" placeholder="请输入文档名称" />
        </el-form-item>
        <el-form-item label="文档链接" prop="url">
          <file-upload
            :disabled="disabled"
            v-model="sortedFileUrl"
            :fileType="getFileType()"
            :fileSize="100"
            :limit="getFileLimit()"
            ref="fileUpload"
            @input="handleFileUrlChange"
          />
        </el-form-item>
        <el-form-item label="文档位置" prop="loc">
          <el-input :disabled="disabled" v-model="form.loc" placeholder="请输入文档位置" />
        </el-form-item>
        <el-form-item label="管理单位" prop="unitId">
          <el-select :disabled="disabled" v-model="form.unitId" placeholder="请选择管理单位">
            <el-option
              v-for="dict in unitOptions"
              :key="dict.unitId"
              :label="dict.name"
              :value="dict.unitId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!disabled" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ disabled ? '关 闭' : '取 消' }}</el-button>
      </div>
    </el-dialog>

    <!-- 文档批量上传对话框 -->
    <el-dialog title="文档批量上传" :visible.sync="batchUploadOpen" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="batchForm" :model="batchForm" :rules="batchRules" label-width="80px">
        <el-form-item label="组卷类别" prop="typeId">
          <treeselect v-model="batchForm.typeId" :options="typeTreeOptions" :show-count="true" placeholder="请选择组卷类别" />
        </el-form-item>
        <el-form-item label="管理单位" prop="unitId">
          <el-select v-model="batchForm.unitId" placeholder="请选择管理单位" clearable>
            <el-option
              v-for="dict in unitOptions"
              :key="dict.unitId"
              :label="dict.name"
              :value="dict.unitId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文档位置" prop="loc">
          <el-input v-model="batchForm.loc" placeholder="请输入文档位置" />
        </el-form-item>
        <el-form-item label="PDF文档" prop="files">
          <el-upload
            ref="batchUpload"
            :auto-upload="false"
            :file-list="batchFileList.length > 100 ? [] : batchFileList"
            :show-file-list="batchFileList.length <= 100"
            :on-change="handleBatchFileChange"
            :on-remove="handleBatchFileRemove"
            :before-upload="beforeBatchUpload"
            :disabled="chunkUploadProgress.isUploading"
            accept=".pdf"
            multiple
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将PDF文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传PDF文件，单个文件不超过5000MB，支持大量文件上传，系统会自动分批处理</div>
          </el-upload>

          <!-- 文件数量显示 -->
          <div v-if="batchFileList.length > 0" style="margin-top: 10px; color: #606266;">
            已选择 <strong>{{ batchFileList.length }}</strong> 个文件
            <span v-if="batchFileList.length > 100">（文件较多，已隐藏文件列表以提升性能）</span>
          </div>
        </el-form-item>

        <!-- 上传进度显示 -->
        <el-form-item v-if="chunkUploadProgress.isUploading || chunkUploadProgress.total > 0">
          <div style="margin-bottom: 10px;">
            <span>上传进度：{{ chunkUploadProgress.current }}/{{ chunkUploadProgress.total }} 批次</span>
            <span style="margin-left: 20px;">已成功：{{ chunkUploadProgress.successCount }} 个文件</span>
          </div>
          <el-progress
            :percentage="chunkUploadProgress.percentage"
            :status="chunkUploadProgress.isUploading ? 'active' : (chunkUploadProgress.current === chunkUploadProgress.total ? 'success' : 'exception')"
          ></el-progress>
          <div v-if="chunkUploadProgress.failedChunks.length > 0" style="margin-top: 10px; color: #f56c6c;">
            失败批次：{{ chunkUploadProgress.failedChunks.join(', ') }}
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitBatchUpload"
          :loading="batchUploading || chunkUploadProgress.isUploading"
          :disabled="chunkUploadProgress.isUploading"
        >
          {{ chunkUploadProgress.isUploading ? '上传中...' : '开始上传' }}
        </el-button>
        <el-button
          @click="cancelBatchUpload"
          :disabled="chunkUploadProgress.isUploading"
        >取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDoc, getDoc, delDoc, addDoc, updateDoc, deptTypeSelect, batchUploadDocs, chunkBatchUploadDocs} from "@/api/system/doc";
import {listUnitDict} from "@/api/system/unit";
import {listType} from "@/api/system/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "Doc",
  dicts: ['sys_job_status'],
  components: { Treeselect, Splitpanes, Pane },
  data() {
    return {
      disabled: false,
      defaultProps: {
        children: "children",
        label: "label"
      },
      typeTreeOptions: undefined,
      typeName: undefined,
      unitOptions:[],
      unitMap:new Map(),
      typeMap:new Map(),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文档表格数据
      docList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeId: null,
        unitId: null,
        name: null,
        loc: null,
        docType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        docType: [
          { required: true, message: "文档类型不能为空", trigger: "change" }
        ],
        typeId: [
          { required: true, message: "组卷类别不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "文档名称不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "文档链接不能为空", trigger: "blur" }
        ],
      },
      // 批量上传相关数据
      batchUploadOpen: false,
      batchUploading: false,
      batchFileList: [],
      batchForm: {
        typeId: null,
        unitId: null,
        loc: null
      },
      batchRules: {
        typeId: [
          { required: true, message: "组卷类别不能为空", trigger: "change" }
        ]
      },
      // 分块上传相关数据
      chunkUploadProgress: {
        current: 0,
        total: 0,
        percentage: 0,
        isUploading: false,
        successCount: 0,
        failedChunks: []
      }
    };
  },
  computed: {
    // 计算排序后的文件URL（仅用于显示）
    sortedFileUrl: {
      get() {
        return this.form.url || '';
      },
      set(value) {
        this.form.url = value;
      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    typeName(val) {
      this.$refs.tree.filter(val);
    },
    // 监听文档链接变化，自动回填文档名称
    'form.url': {
      handler(newVal, oldVal) {
        // 只处理PDF文档类型
        if (this.form.docType === '1') {
          // 如果文件被删除（从有值变成空值），清空文档名称
          if (oldVal && !newVal) {
            this.form.name = null;
            console.log('文件已删除，清空文档名称');
          }
          // 如果是新上传的文件，自动填写文档名称
          else if (newVal && newVal !== oldVal) {
            // 延迟执行，确保文件上传完成
            setTimeout(() => {
              this.autoFillDocName();
            }, 100);
          }
        }
      },
      immediate: false
    }
  },
  created() {
    this.getList();
    this.getUnitList();
    this.getTypeList();
    this.getTypeTree();
  },
  methods: {
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.typeId = data.id;
      this.handleQuery();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询部门下拉树结构 */
    getTypeTree() {
      deptTypeSelect().then(response => {
        this.typeTreeOptions = response.data;
      });
    },
    getUnit(unitId){
      let name = "";
      name = this.unitMap.get(unitId);
      return name;
    },
    getType(typeId){
      let name = "";
      name = this.typeMap.get(typeId);
      return name;
    },
    getDocTypeName(docType){
      if(docType == '1') {
        return 'PDF型';
      } else if(docType == '2') {
        return '图片型';
      }
      return '';
    },

    /** 查询文档列表 */
    getList() {
      this.loading = true;
      listDoc(this.queryParams).then(response => {
        this.docList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询管理单位列表 */
    getUnitList() {
      listUnitDict().then(response => {
        this.unitOptions = response.data;
        let dataMap = new Map();
        this.unitOptions.forEach(item => {
          dataMap.set(item.unitId,item.name);
        });
        this.unitMap = dataMap;
      });
    },
    getTypeList() {
      listType().then(response => {
        let data = response.data;
        let dataMap = new Map();
        data.forEach(item => {
          dataMap.set(item.typeId,item.name);
        });
        this.typeMap = dataMap;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        docId: null,
        docType: null,
        typeId: null,
        unitId: null,
        name: null,
        loc: null,
        url: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.docId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.disabled = false;
      this.open = true;
      this.title = "添加文档";
    },
    handleView(row) {
      this.reset();
      this.disabled = true;
      const docId = row.docId || this.ids
      getDoc(docId).then(response => {
        this.form = response.data;
        // 如果是图片类型，排序文件
        this.$nextTick(() => {
          this.sortImageFiles();
        });
        this.open = true;
        this.title = "查看文档";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.disabled = false;
      const docId = row.docId || this.ids
      getDoc(docId).then(response => {
        this.form = response.data;
        // 如果是图片类型，排序文件
        this.$nextTick(() => {
          this.sortImageFiles();
        });
        this.open = true;
        this.title = "修改文档";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.docId != null) {
            updateDoc(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDoc(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const docIds = row.docId || this.ids;
      this.$modal.confirm('是否确认删除文档编号为"' + docIds + '"的数据项？').then(function() {
        return delDoc(docIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/doc/export', {
        ...this.queryParams
      }, `doc_${new Date().getTime()}.xlsx`)
    },
    // 文档类型变化处理
    handleDocTypeChange(value) {
      // 如果有现有文件且切换到图片型，进行排序
      if (value === '2' && this.form.url) {
        this.$nextTick(() => {
          this.sortImageFiles();
        });
      } else {
        // 清空文档链接
        this.form.url = null;
      }

      // 如果是图片型，清空文档名称
      if (value === '2') {
        this.form.name = null;
      }
      // 如果切换到PDF型且没有文档名称，后续会通过watch自动填写
    },
    // 获取文件类型限制
    getFileType() {
      if (this.form.docType === '1') {
        return ['pdf'];
      } else if (this.form.docType === '2') {
        return ['jpg', 'png', 'jpeg', 'gif'];
      }
      return ['pdf', 'jpg', 'png', 'jpeg', 'gif'];
    },
    // 获取文件数量限制
    getFileLimit() {
      if (this.form.docType === '1') {
        return 1;
      } else if (this.form.docType === '2') {
        return 500;
      }
      return 1;
    },
    // 自动填写文档名称
    autoFillDocName() {
      if (this.form.docType === '1' && this.form.url) {
        let fileName = '';

        // 方法1：尝试从FileUpload组件的fileList获取文件名
        try {
          if (this.$refs.fileUpload && this.$refs.fileUpload.fileList && this.$refs.fileUpload.fileList.length > 0) {
            const lastFile = this.$refs.fileUpload.fileList[this.$refs.fileUpload.fileList.length - 1];
            if (lastFile && lastFile.name) {
              fileName = this.getFileNameFromPath(lastFile.name);
            }
          }
        } catch (e) {
          console.log('从fileList获取文件名失败:', e);
        }

        // 方法2：如果方法1失败，从URL中提取文件名
        if (!fileName && this.form.url) {
          const urlParts = this.form.url.split(',');
          if (urlParts.length > 0) {
            const lastUrl = urlParts[urlParts.length - 1].trim();
            fileName = this.getFileNameFromPath(lastUrl);
          }
        }

        if (fileName) {
          // 去掉文件后缀，得到文档名称
          const nameWithoutExt = fileName.replace(/\.[^/.]+$/, "");
          if (nameWithoutExt) {
            this.form.name = nameWithoutExt;
            console.log('自动填写文档名称:', nameWithoutExt);
          }
        }
      }
    },
    // 从文件路径中提取文件名
    getFileNameFromPath(path) {
      if (!path) return '';
      // 处理URL路径，取最后的文件名部分
      if (path.includes('/')) {
        return path.split('/').pop();
      }
      // 处理Windows路径
      if (path.includes('\\')) {
        return path.split('\\').pop();
      }
      return path;
    },
    // 批量上传按钮操作
    handleBatchUpload() {
      this.batchUploadOpen = true;
      this.resetBatchForm();
      this.resetBatchUpload();
    },
    // 批量上传文件变化
    handleBatchFileChange(file, fileList) {
      // 限制最大文件数量
      const maxFiles = 1500;
      if (fileList.length > maxFiles) {
        this.$modal.msgWarning(`为了确保系统稳定性，单次最多支持上传${maxFiles}个文件。当前选择了${fileList.length}个文件，请分批上传。`);
        // 只保留前maxFiles个文件
        this.batchFileList = fileList.slice(0, maxFiles);
        // 更新el-upload的显示
        this.$nextTick(() => {
          if (this.$refs.batchUpload) {
            this.$refs.batchUpload.uploadFiles = this.batchFileList;
          }
        });
        return;
      }

      this.batchFileList = fileList;
      console.log(`文件选择完成: 共${fileList.length}个文件`);
    },
    // 批量上传文件移除
    handleBatchFileRemove(file, fileList) {
      this.batchFileList = fileList;
    },
    // 批量上传前验证
    beforeBatchUpload(file) {
      const isPDF = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf');
      if (!isPDF) {
        this.$modal.msgError('只能上传PDF格式的文件!');
        return false;
      }
      const isLt5000M = file.size / 1024 / 1024 < (50*100);
      if (!isLt5000M) {
        this.$modal.msgError('上传文件大小不能超过 5000MB!');
        return false;
      }
      return true;
    },
    // 提交批量上传
    submitBatchUpload() {
      this.$refs["batchForm"].validate(valid => {
        if (valid) {
          if (this.batchFileList.length === 0) {
            this.$modal.msgError("请选择要上传的PDF文件！");
            return;
          }

          // 检查文件数量，决定使用哪种上传方式
          const fileCount = this.batchFileList.length;
          console.log(`批量上传: 文件总数=${fileCount}`);

          // 对超大量文件给予特别提醒
          if (fileCount > 500) {
            this.$modal.confirm(`您选择了${fileCount}个文件，这将需要较长时间上传。建议您：\n1. 确保网络连接稳定\n2. 不要关闭浏览器页面\n3. 耐心等待上传完成\n\n是否继续？`).then(() => {
              this.executeUpload(fileCount);
            }).catch(() => {
              console.log('用户取消了大量文件上传');
            });
          } else {
            this.executeUpload(fileCount);
          }
        }
      });
    },

    // 执行上传
    executeUpload(fileCount) {
      if (fileCount <= 18) {
        // 少量文件直接上传（平衡阈值）
        console.log('使用直接批量上传模式');
        this.directBatchUpload();
      } else {
        // 大量文件分块上传
        console.log('使用分块批量上传模式');
        this.chunkBatchUpload();
      }
    },

    // 直接批量上传（少量文件）
    directBatchUpload() {
      this.batchUploading = true;
      this.$modal.loading("正在上传文件，请稍候...");

      // 创建FormData
      const formData = new FormData();
      formData.append('typeId', this.batchForm.typeId);
      if (this.batchForm.unitId) {
        formData.append('unitId', this.batchForm.unitId);
      }
      if (this.batchForm.loc) {
        formData.append('loc', this.batchForm.loc);
      }

      // 添加文件
      this.batchFileList.forEach(fileItem => {
        formData.append('files', fileItem.raw);
      });

      // 调用批量上传接口
      batchUploadDocs(formData).then(response => {
        this.batchUploading = false;
        this.$modal.closeLoading();
        this.batchUploadOpen = false;
        this.$modal.msgSuccess(`批量上传成功！共上传 ${response.data} 个文件`);
        this.getList(); // 刷新列表
        this.resetBatchUpload();
      }).catch(error => {
        this.batchUploading = false;
        this.$modal.closeLoading();
        this.$modal.msgError("批量上传失败：" + (error.msg || error.message));
      });
    },

    // 分块批量上传（大量文件）
    async chunkBatchUpload() {
      try {
        const fileCount = this.batchFileList.length;
        // 优化配置：在新的5000MB限制下可以处理更多文件
        let chunkSize = 15; // 保守的默认批次大小，考虑文件可能更大
        if (fileCount > 1000) {
          chunkSize = 12; // 大量文件时减少批次大小
        } else if (fileCount > 500) {
          chunkSize = 15; // 中等数量使用标准批次
        } else {
          chunkSize = 18; // 少量文件时可以增加批次大小
        }

        const totalChunks = Math.ceil(fileCount / chunkSize);

        console.log(`开始分块上传: 文件总数=${fileCount}, 分块大小=${chunkSize}, 总批次=${totalChunks}`);

        // 计算总数据量
        const totalSize = this.batchFileList.reduce((sum, file) => sum + (file.size || 0), 0);
        const totalSizeMB = Math.round(totalSize / 1024 / 1024);
        console.log(`总数据量: ${totalSizeMB}MB`);

        // 内存使用监控（如果浏览器支持）
        if (performance && performance.memory) {
          const memInfo = performance.memory;
          console.log(`内存使用: ${Math.round(memInfo.usedJSHeapSize / 1024 / 1024)}MB / ${Math.round(memInfo.totalJSHeapSize / 1024 / 1024)}MB`);
        }

        // 初始化进度
        this.chunkUploadProgress = {
          current: 0,
          total: totalChunks,
          percentage: 0,
          isUploading: true,
          successCount: 0,
          failedChunks: []
        };

        this.$modal.msg(`开始分批上传，共${fileCount}个文件(${totalSizeMB}MB)，将分为${totalChunks}批进行上传`);

        // 分批上传
        for (let i = 0; i < totalChunks; i++) {
          const startIndex = i * chunkSize;
          const endIndex = Math.min(startIndex + chunkSize, fileCount);
          const chunkFiles = this.batchFileList.slice(startIndex, endIndex);

          const chunkSize_MB = Math.round(chunkFiles.reduce((sum, file) => sum + (file.size || 0), 0) / 1024 / 1024);
          console.log(`准备上传第${i + 1}/${totalChunks}批, 文件数量: ${chunkFiles.length}, 大小: ${chunkSize_MB}MB`);
          console.log(`当前累计成功: ${this.chunkUploadProgress.successCount}个文件`);

          try {
            const response = await this.uploadChunk(chunkFiles, i, totalChunks);
            this.chunkUploadProgress.current = i + 1;
            this.chunkUploadProgress.percentage = Math.round(((i + 1) / totalChunks) * 100);
            console.log(`第${i + 1}批上传成功, 当前进度: ${this.chunkUploadProgress.percentage}%, 累计成功: ${this.chunkUploadProgress.successCount}个文件`);

            // 强制更新UI
            this.$forceUpdate();

            // 平衡延迟：既要稳定又不能太慢
            if (i < totalChunks - 1) {
              let delay = 500; // 平衡的延迟时间
              if (chunkSize >= 15) {
                delay = 600; // 较大批次稍长一点
              } else {
                delay = 500; // 较小批次标准延迟
              }

              // 每处理10批后建议垃圾回收（因为每批文件更多）
              if ((i + 1) % 10 === 0 && window.gc) {
                console.log(`第${i + 1}批完成，执行垃圾回收`);
                try {
                  window.gc();
                } catch (e) {
                  // 忽略垃圾回收错误
                }
              }

              await new Promise(resolve => setTimeout(resolve, delay));
            }
          } catch (error) {
            console.error(`第${i + 1}批上传失败:`, error);
            this.chunkUploadProgress.failedChunks.push(i + 1);

            // 如果是网络错误，增加重试机制
            if (error.message && error.message.includes('timeout')) {
              console.log(`第${i + 1}批因超时失败，等待2秒后继续下一批`);
              await new Promise(resolve => setTimeout(resolve, 2000));
            }
          }
        }

        // 上传完成
        this.chunkUploadProgress.isUploading = false;
        console.log(`上传完成: 成功=${this.chunkUploadProgress.successCount}, 失败批次=${this.chunkUploadProgress.failedChunks}`);

        if (this.chunkUploadProgress.failedChunks.length === 0) {
          this.$modal.msgSuccess(`所有文件上传完成！共成功上传 ${this.chunkUploadProgress.successCount} 个文件`);
          this.batchUploadOpen = false;
          this.getList();
          this.resetBatchUpload();
        } else {
          this.$modal.msgWarning(`部分批次上传失败，成功上传 ${this.chunkUploadProgress.successCount} 个文件。失败批次：${this.chunkUploadProgress.failedChunks.join(', ')}`);
        }
      } catch (error) {
        console.error('分块上传过程中出现严重错误:', error);
        this.chunkUploadProgress.isUploading = false;
        this.$modal.msgError('上传过程中出现严重错误: ' + error.message);
      }
    },

    // 上传单个批次
    uploadChunk(chunkFiles, chunkIndex, totalChunks) {
      return new Promise((resolve, reject) => {
        try {
          const chunkStartTime = Date.now();
          console.log(`开始构建第${chunkIndex + 1}批FormData...`);

          // 创建FormData
          const formData = new FormData();
          formData.append('typeId', this.batchForm.typeId);
          if (this.batchForm.unitId) {
            formData.append('unitId', this.batchForm.unitId);
          }
          if (this.batchForm.loc) {
            formData.append('loc', this.batchForm.loc);
          }
        formData.append('chunkIndex', chunkIndex);
        formData.append('totalChunks', totalChunks);
        formData.append('totalFiles', this.batchFileList.length); // 添加总文件数量

        // 添加文件
          let totalFileSize = 0;
          chunkFiles.forEach((fileItem, index) => {
            if (fileItem.raw) {
              formData.append('files', fileItem.raw);
              totalFileSize += fileItem.raw.size;
              console.log(`  文件${index + 1}: ${fileItem.name}, 大小: ${Math.round(fileItem.raw.size / 1024 / 1024)}MB`);
            } else {
              console.warn(`  文件${index + 1}: ${fileItem.name} 没有raw对象`);
            }
          });

          const formDataTime = Date.now();
          console.log(`第${chunkIndex + 1}批FormData构建完成, 总大小: ${Math.round(totalFileSize / 1024 / 1024)}MB, 构建耗时: ${formDataTime - chunkStartTime}ms`);
          console.log(`正在发送第${chunkIndex + 1}批请求到后端...`);

          // 调用分块上传接口
          chunkBatchUploadDocs(formData).then(response => {
            const responseTime = Date.now();
            const totalChunkTime = responseTime - chunkStartTime;
            const networkTime = totalChunkTime - (formDataTime - chunkStartTime);
            console.log(`第${chunkIndex + 1}批上传成功, 总耗时: ${totalChunkTime}ms, 网络传输: ${networkTime}ms`, response);

            // 修复进度显示：直接使用response.data作为上传成功数量
            let uploadedCount = 0;
            if (response && response.data) {
              if (typeof response.data === 'number') {
                // 后端直接返回数字
                uploadedCount = response.data;
              } else if (typeof response.data.uploadedCount === 'number') {
                // 后端返回对象包含uploadedCount
                uploadedCount = response.data.uploadedCount;
              } else {
                // 兜底：使用当前批次文件数量
                uploadedCount = chunkFiles.length;
              }
            } else {
              uploadedCount = chunkFiles.length;
            }

            this.chunkUploadProgress.successCount += uploadedCount;
            console.log(`第${chunkIndex + 1}批成功上传${uploadedCount}个文件，总计：${this.chunkUploadProgress.successCount}`);
            resolve(response);
          }).catch(error => {
            console.error(`第${chunkIndex + 1}批上传失败:`, error);
            if (error.response) {
              console.error(`响应状态: ${error.response.status}`, error.response.data);
            }
            if (error.request) {
              console.error(`请求详情:`, error.request);
            }
            reject(error);
          });
        } catch (error) {
          console.error(`构建第${chunkIndex + 1}批FormData时出错:`, error);
          reject(error);
        }
      });
    },

    // 重置批量上传状态
    resetBatchUpload() {
      this.chunkUploadProgress = {
        current: 0,
        total: 0,
        percentage: 0,
        isUploading: false,
        successCount: 0,
        failedChunks: []
      };
    },
    // 取消批量上传
    cancelBatchUpload() {
      if (this.chunkUploadProgress.isUploading) {
        this.$modal.confirm('正在上传中，确定要取消吗？').then(() => {
          this.batchUploadOpen = false;
          this.resetBatchUpload();
          this.resetBatchForm();
        }).catch(() => {});
      } else {
        this.batchUploadOpen = false;
        this.resetBatchUpload();
        this.resetBatchForm();
      }
    },

    // 重置批量上传表单
    resetBatchForm() {
      this.batchForm = {
        typeId: null,
        unitId: null,
        loc: null
      };
      this.batchFileList = [];
      this.batchUploading = false;
    },
    // 处理文件URL变化
    handleFileUrlChange(value) {
      this.form.url = value;

      // 如果是图片类型且有多个文件，自动排序
      if (this.form.docType === '2' && value && value.includes(',')) {
        this.$nextTick(() => {
          this.sortImageFiles();
        });
      }
    },
    // 对图片文件进行排序
    sortImageFiles() {
      if (this.form.docType === '2' && this.form.url) {
        const urls = this.form.url.split(',').filter(url => url.trim());
        if (urls.length > 1) {
          const sortedUrls = urls.sort((a, b) => {
            const nameA = this.getFileNameFromPath(a.trim()).toLowerCase();
            const nameB = this.getFileNameFromPath(b.trim()).toLowerCase();
            return nameA.localeCompare(nameB);
          });
          const sortedUrl = sortedUrls.join(',');

          // 只有当排序后的URL与原URL不同时才更新
          if (sortedUrl !== this.form.url) {
            this.form.url = sortedUrl;
            console.log('图片文件已按文件名排序');
          }
        }
      }
    }
  }
};
</script>
